###########################################
## ESTIMACIONES Y PROYECCIONES DE POBLACIÓN
## Indicadores Demográficos – Nivel Nacional
## 
##
## Elaborado por: Alexander Oviedo
###########################################

# =========================================================
# 1. LIMPIEZA DEL ENTORNO
# =========================================================
rm(list = ls())
gc()

# =========================================================
# 2. LIBRERÍAS
# =========================================================
library(readxl)
library(openxlsx)

options(scipen = 999)
Sys.setenv("R_ZIPCMD" = "C:/Rtools/bin/zip.exe")

# =========================================================
# 3. RUTAS
# =========================================================
ruta_origen     <- "bdd/Tabulado_proyec_nacional_1950_2050.xlsx"
ruta_plantilla  <- "bdd/plantilla/plantilla_indicadores_demogra_nac.xlsx"
ruta_salida     <- "out/plantilla_indicadores_nacional.xlsx"

dir.create("out", showWarnings = FALSE)

# =========================================================
# 4. DECIMALES POR INDICADOR 
#    
# =========================================================
decimales_fila <- list(
  `12` = 2,  # Edad Media
  `13` = 2,  # Relación de Dependencia
  `14` = 2,  # Índice de Envejecimiento
  `15` = 2,  # Razón de Sexos
  `17` = 0,  # Nacimientos Anuales
  `18` = 2,  # Tasa Bruta de Natalidad
  `19` = 2,  # Tasa Global de Fecundidad
  `21` = 0,  # Defunciones Anuales
  `22` = 2,  # Tasa Bruta de Mortalidad
  `24` = 1,  # Esperanza de Vida (Ambos)
  `25` = 1,  # Esperanza de Vida (Hombres)
  `26` = 1,  # Esperanza de Vida (Mujeres)
  `28` = 0,  # Saldo Migratorio Neto
  `29` = 2   # Tasa Neta de Migración
)

# =========================================================
# 5. BLOQUES A COPIAR
# =========================================================
bloques <- list(
  list(inicio = 12, fin = 15),
  list(inicio = 17, fin = 19),
  list(inicio = 21, fin = 26),
  list(inicio = 28, fin = 29)
)

# =========================================================
# 6. ABRIR PLANTILLA
# =========================================================
wb <- loadWorkbook(ruta_plantilla)

# =========================================================
# 7. COPIAR BLOQUES - APLICAR DECIMALES
# =========================================================
for (b in bloques) {
  
  fila_inicio <- b$inicio
  fila_fin    <- b$fin
  
  rango <- paste0("C", fila_inicio, ":CY", fila_fin)
  
  datos <- read_excel(
    path  = ruta_origen,
    sheet = "ind_demogra",
    range = rango,
    col_names = FALSE
  )
  
  datos <- as.data.frame(datos)
  
  # Aplicar decimales fila por fila
  for (i in seq_len(nrow(datos))) {
    
    fila_real <- fila_inicio + i - 1
    dec <- decimales_fila[[as.character(fila_real)]]
    
    if (!is.null(dec)) {
      datos[i, ] <- round(as.numeric(datos[i, ]), dec)
    }
  }
  
  # Escribir SOLO el bloque tratado
  writeData(
    wb,
    sheet    = "ind_demogra",
    x        = datos,
    startCol = "C",
    startRow = fila_inicio,
    colNames = FALSE
  )
  
  cat("Bloque copiado y redondeado: filas", fila_inicio, "a", fila_fin, "\n")
}

# =========================================================
# 8. GUARDAR ARCHIVO FINAL
# =========================================================
saveWorkbook(
  wb,
  ruta_salida,
  overwrite = TRUE
)

cat("Proceso finalizado correctamente\n")
cat("Archivo generado en:", ruta_salida, "\n")

